package com.caul.demo.hbase.bulkload;

import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.util.Map;

/**
 * 将数据导入到HDFS中, 导入格式是HFILE,供HBase读取
 * Created by sdliang on 2018/4/19.
 */
public class ImportMapper extends Mapper<LongWritable, Text, ImmutableBytesWritable, Put> {

  ObjectMapper objectMapper;

  @Override
  protected void setup(Context context) throws IOException, InterruptedException {
    objectMapper = new ObjectMapper();
  }

  /**
   * @param key
   * @param value   rowId {"family.key1":value1,"family.key2":value2}
   * @param context
   * @throws IOException
   * @throws InterruptedException
   */
  @Override
  protected void map(LongWritable key, Text value, Context context)
      throws IOException, InterruptedException {
    String[] split = value.toString().split("\t");
    byte[] rowKey = Bytes.toBytes(split[0]);
    ImmutableBytesWritable rowId = new ImmutableBytesWritable(rowKey);

    Put put = new Put(rowKey);
    Map<String, String> valueMap = objectMapper.readValue(split[1], Map.class);
    valueMap.forEach((k, v) -> {
      String[] col = k.split("\\.");
      put.addColumn(Bytes.toBytes(col[0]), Bytes.toBytes(col[1]), Bytes.toBytes(v));
    });
    context.write(rowId, put);
  }
}
